package jsyf.oa.service.capital;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.capital.BankCardDao;
import jsyf.oa.dao.capital.BankDebitsDao;
import jsyf.oa.dao.capital.FlowDao;
import jsyf.oa.entity.capital.FlowEntity;
import jsyf.oa.facade.capital.FlowFacade;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by houtailei on 2018/2/25.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class FlowService implements FlowFacade {
    @Autowired
    private FlowDao flowDao;
    @Autowired
    private BankCardDao bankCardDao;
    @Autowired
    private BankDebitsDao bankDebitsDao;

    @Override
    public String addFlow(String jsonData) {
        List<FlowEntity> entity = (List<FlowEntity>) JSONArray.toCollection(JSONArray.fromObject(jsonData), FlowEntity.class);
        for (int i = 0; i < entity.size(); i++) {
            FlowEntity model = entity.get(i);
            model.setDelFlag(0);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                model.setCreateTime(simpleDateFormat.parse(model.getNewTime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            flowDao.addFlow(model);
        }
        return "true";
    }

    @Override
    public String detailFlow(String jsonData) {
        FlowEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), FlowEntity.class);
        FlowEntity oldEntity = (FlowEntity) flowDao.getIBaseEntityById(entity.getId());
        oldEntity.setDelFlag(1);
        oldEntity.setRemark(entity.getRemark());
        flowDao.update(oldEntity);
        return entity.getId();
    }

    @Override
    public String removeFlow(String jsonData) {
        FlowEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), FlowEntity.class);
        return flowDao.removeById(entity.getId())+"";
    }

    @Override
    public String updateFlow(String jsonData) {
        FlowEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), FlowEntity.class);
        FlowEntity oldEntity = (FlowEntity) flowDao.getIBaseEntityById(entity.getId());
        oldEntity.setDelFlag(entity.getDelFlag());
        oldEntity.setMoney(entity.getMoney());
        oldEntity.setProject(entity.getProject());
        flowDao.update(oldEntity);
        return entity.getId();
    }

    @Override
    public String transferAccounts(String jsonData) {
        List<FlowEntity> entity = (List<FlowEntity>) JSONArray.toCollection(JSONArray.fromObject(jsonData), FlowEntity.class);
        for (int i = 0; i < entity.size(); i++) {
            FlowEntity model = entity.get(i);
            model.setDelFlag(0);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                model.setCreateTime(simpleDateFormat.parse(model.getNewTime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            model.setFlowDirection("0");
            model.setTkBankCardId(model.getTkBankCardId());
            model.setProject("转入-"+model.getTkOutBankCardName());
            flowDao.addFlow(model);
            model.setFlowDirection("1");
            model.setTkBankCardId(model.getTkOutBankCardId());
            model.setProject(model.getTkBankCardName()+"-转入");
            flowDao.addFlow(model);
        }
        return "true";
    }

    @Override
    public JSONObject getFlowList(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject result = new JSONObject();
        JSONObject objSendData = new JSONObject();
        String requestPage;
        String pageSize;
        if (jsonParams.containsKey("requestPage") && jsonParams.containsKey("pageSize")) {
            requestPage = jsonParams.getString("requestPage");
            pageSize = jsonParams.getString("pageSize");
        } else {
            requestPage = "1";
            pageSize = Integer.MAX_VALUE + "";
        }
        String companyId = jsonParams.getString("fkCompanyId");
        String bankCardId = jsonParams.getString("tkBankCardId");
        String money = jsonParams.getString("money");
        String project = jsonParams.getString("project");
        String flowDirection = jsonParams.getString("flowDirection");
        String beginTime = jsonParams.getString("beginTime");

        String endTime = jsonParams.getString("endTime");

        List<Object> sqlArgs = new ArrayList<>();
        StringBuffer sql = new StringBuffer();

        if (StringUtils.isNotBlank(beginTime)){
            sql.append(" AND flow.CREATE_TIME<=? \n");
            sqlArgs.add(beginTime);
        }
        if (StringUtils.isNotBlank(endTime)){
            sql.append(" AND flow.CREATE_TIME>=? \n");
            sqlArgs.add(endTime);
        }
        if (StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime)) {
            sql.append(" AND flow.CREATE_TIME BETWEEN ? AND ? \n");
            sqlArgs.add(beginTime);
            sqlArgs.add(endTime);
        }
        if (StringUtils.isNotBlank(money)) {
            sql.append(" AND flow.MONEY like ? \n");
            sqlArgs.add("%" + money + "%");
        }
        if (StringUtils.isNotBlank(project)) {
            sql.append(" AND flow.PROJECT like ? \n");
            sqlArgs.add("%" + project + "%");
        }
        if (StringUtils.isNotBlank(companyId)) {
            sql.append(" AND bank.FK_COMPANY_ID= ? \n");
            sqlArgs.add(companyId);
        }
        if (StringUtils.isNotBlank(bankCardId)) {
            sql.append(" AND bank.BANK_CARD= ? \n");
            sqlArgs.add(bankCardId);
        }
        if (StringUtils.isNotBlank(flowDirection)) {
            sql.append(" AND flow.FLOW_DIRECTION= ? \n");
            sqlArgs.add(flowDirection);
        }
        sql.append("order by flow.CREATE_TIME desc \n");
        List<JSONObject> records =flowDao.getFlowList(sql.toString(), sqlArgs.toArray(),Integer.parseInt(requestPage), Integer.parseInt(pageSize));
        int recordCount = flowDao.getFlowListCount(sql.toString(), sqlArgs.toArray());
        int recordSize = Integer.valueOf(pageSize).intValue();
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % recordSize == 0 ? recordCount / recordSize : (recordCount / recordSize) + 1;
        //子对象
        objSendData.put("recordCount", recordCount);
        objSendData.put("pageCount", pageCount);
        objSendData.put("requestPage", 1);
        result.put("pager", objSendData);
        // 子数组对象
        result.put("records", records);
        return result;
    }

    @Override
    public List<JSONObject> getBankCardListAndFlowList(String companyId, String date) throws ParseException {
        //承兑汇票
//        List<JSONObject> bankDebits = bankDebitsDao.getJSONListByCondition(" and FK_COMPANY_ID=? and CREATE_TIME like ?", new Object[]{companyId, "%" + date + "%"});
//        List<JSONObject> bankDebitsFirst = new ArrayList<>();
//        List<JSONObject> bankDebitsZero = new ArrayList<>();
//        for (Integer i = 0; i < bankDebits.size(); i++) {
//            JSONObject bankDebitsJson = bankDebits.get(i);
//            if ("1".equals(flowJson.getString("flowDirection"))) {
//                flowFirst.add(flowJson);
//            } else {
//                flowZero.add(flowJson);
//            }
//        }
        List<JSONObject> list = bankCardDao.getJSONListByCondition(" AND FK_COMPANY_ID = ? AND USE_STATUS= 1", new Object[]{companyId});
        for (Integer i = 0; i < list.size(); i++) {
            String cardId = list.get(i).get("id").toString();
            //查询银行卡
            JSONObject result = new JSONObject();
            List<JSONObject> flowFirst = new ArrayList<>();
            List<JSONObject> flowZero = new ArrayList<>();
            Integer number = 0;
            float totalIncome = 0;
            float totalPay = 0;
            List<JSONObject> flowList = flowDao.getJSONListByCondition(" AND LEFT(CREATE_TIME,10)=? AND TK_BANK_CARD_ID=? AND DEL_FLAG=0", new Object[]{date, cardId});
            if (flowList.size() > 0) {
                for (int j = 0; j < flowList.size(); j++) {
                    JSONObject flowJson = flowList.get(j);
                    if ("1".equals(flowJson.getString("flowDirection"))) {
                        flowFirst.add(flowJson);
                        totalIncome += flowJson.getFloat("money");
                    } else {
                        flowZero.add(flowJson);
                        totalPay += flowJson.getFloat("money");
                    }
                }
                if (flowFirst.size() > flowZero.size()) {
                    number = flowFirst.size();
                } else {
                    number = flowZero.size();
                }
                result.put("flowFirst", flowFirst);
                result.put("flowZero", flowZero);
                result.put("totalIncome", totalIncome);
                result.put("totalPay", totalPay);
                result.put("number", number);
            }
            result.put("yestdayBalance", flowDao.getbalance(cardId,getYesterDay(date)));
            result.put("todayBalance", flowDao.getbalance(cardId, date));
            list.get(i).put("flowList", result);
        }



//       List<BankCardEntity>  cardList =  bankCardDao.getEntityListByCondition(" AND FK_COMPANY_ID = ? ",new Object[]{companyId});
//       for(Integer i = 0; i < cardList.size();i++){
//           BankCardEntity cardEntity = cardList.get(i);
//           List<FlowEntity> flowList = flowDao.getEntityListByCondition(" AND LEFT(CREATE_TIME,10)=? AND TK_BANK_CARD_ID=?",new Object[]{date,cardEntity.getId()});
//           cardEntity.setFlowList(flowList);
//       }
//        JSONObject result = new JSONObject();
//        result.put("list",cardList);


        return list;
    }

    public String getYesterDay(String dateString) throws ParseException {
        //通过传过来的时间算出前一天
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        Date dayCurrent = format1.parse(dateString);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dayCurrent);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        dayCurrent = calendar.getTime();
        return sdf.format(dayCurrent);
    }

}
